package com.topisv.tms.utils.sms;


import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;


/**
 * 短信通知
 * 
 * @author Hakeny
 */
public class SMSTool {

  private static final Logger log = LoggerFactory.getLogger(SMSTool.class);
  private static final String UID = "3291"; // 账号
  private static final String PSW = "sz80257"; // 密码
  private static final String URL = "http://kltx.sms10000.com.cn/sdk/SMS?"; // 请求路径

  public static final String VERIFICATION_CODE = "您的验证码是%s。如非本人操作，请忽略本短信【本消息来自微派送|微便利】";

  public static final String ALISHOPUSER_RESET_PASSWORD = "您的密码已被重置为%s。请及时修改您的密码【本消息来自微派送|微便利】";

  public static final String INVITE_CODE = "快递员%s邀请您使用微便利app客户端，微便利让您的生活更简单【本消息来自微派送】";

  public static final String INVITE_MSG = "%邀请您使用微派送app客户端【本消息来自微派送】";

  private static final String UID_V2 = "ZENYPU"; // 账号
  private static final String PSW_V2 = "123456"; // 密码
  private static final String URL_V2 =
      "http://sms.zenyex.com:8082/MWGate/wmgw.asmx/MongateCsSpSendSmsNew?"; // 请求路径



  public SMSTool() {}

  public static String httpGet(String strURL) {
    String re = "";
    HttpURLConnection urlConn = null;
    InputStream in = null;
    List<String> list = new ArrayList<String>();
    try {
      URL url = new URL(strURL);
      urlConn = (HttpURLConnection) url.openConnection();
      urlConn.setDoOutput(true);
      urlConn.setConnectTimeout(1000);
      urlConn.setRequestMethod("GET");
      in = urlConn.getInputStream();
      BufferedReader rd = new BufferedReader(new InputStreamReader(in, "GBK"));
      String line = rd.readLine();
      while (line != null) {
        line = line.trim();
        if (!line.equals("")) {
          list.add(line);
        }
        line = rd.readLine();
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (in != null)
        try {
          in.close();
        } catch (IOException e) {
        }

      if (urlConn != null) {
        urlConn.disconnect();
      }
    }

    if (list != null && list.size() > 0) {
      for (int i = 0; i < list.size(); i++) {
        re += list.get(i) + "\n";
      }
    }

    return re.trim();
  }

  public static String httpPost(String host, String data) {
    String result = "";
    try {
      URL url = new URL(host);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setDoOutput(true);
      connection.setDoInput(true);
      connection.setReadTimeout(2000);
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-type", "text/xml,charet=gbk");
      connection.setRequestProperty("user-Agent",
          "Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.4223)");
      // SEND DNS INFO
      OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "GBK");
      out.write(data);// SEND DATA
      out.flush();
      out.close();
      // GET RESPONSE
      InputStream in = connection.getInputStream();
      BufferedReader rd = new BufferedReader(new InputStreamReader(in, "GBK"));
      String line = rd.readLine();
      List<String> list = new ArrayList<String>();
      while (line != null) {
        line = line.trim();
        if (!line.equals("")) {
          list.add(line);
        }
        line = rd.readLine();
      }
      if (list != null && list.size() > 0) {
        for (int i = 0; i < list.size(); i++) {
          result += list.get(i) + "\n";
        }
      }
    } catch (MalformedURLException e) {

      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {

      e.printStackTrace();
    } catch (IOException e) {

      e.printStackTrace();
    }

    return result;
  }

  public static String revSMS(String uid, String pwd) {
    String url =
        "http://kltx.sms10000.com.cn/sdk/SMS?cmd=getmo&uid=" + uid + "&psw=" + MD5Encode(pwd);
    String revsms = httpGet(url);
    return revsms;

  }

  public static String revStatus(String uid, String pwd) {
    String url =
        "http://kltx.sms10000.com.cn/sdk/SMS?cmd=getstatus&uid=" + uid + "&psw=" + MD5Encode(pwd);
    String revsms = httpGet(url);
    // String url="http://kltx.sms10000.com.cn/sdk/SMS";
    // String data="cmd=getstatus&uid="+uid+"&psw="+MD5Encode(pwd);
    // String revsms=httpPost(url,data);
    return revsms;
  }

  /**
   * MD5 加 密
   * 
   * @param origin
   * @return
   */
  private static String MD5Encode(String origin) {
    String resultString = null;

    try {
      resultString = new String(origin);
      MessageDigest md = MessageDigest.getInstance("MD5");
      resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
    } catch (Exception ex) {

    }
    return resultString;
  }

  /**
   * 加密字节转换
   * 
   * @param b
   * @return
   */
  private static String byteToHexString(byte b) {
    int n = b;
    if (n < 0) {
      n = 256 + n;
    }
    int d1 = n / 16;
    int d2 = n % 16;
    return hexDigits[d1] + hexDigits[d2];
  }

  public static String byteArrayToHexString(byte[] b) {
    StringBuffer resultSb = new StringBuffer();
    for (int i = 0; i < b.length; i++) {
      resultSb.append(byteToHexString(b[i]));
    }
    return resultSb.toString();
  }

  private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a",
      "b", "c", "d", "e", "f"};

  /**
   * 发 送 短 信 （Get方式）
   * 
   * @param mobile 电话号码，多个电话号码可以用逗号","分隔
   * @param content 短信类容
   * @return 状态码 （100 成功 101失败 102验证失败(密码不对) 103号码有错(接收号码格式错误) 104内容有错(敏感内容) 105操作频率过快(每秒十次)
   *         106限制发送(无条数) 107参数不全）
   */
  public static String sendMsgByGet(String mobile, String content) {
    boolean flag = false;
    if (flag) {
      String pswMd5 = MD5Encode(SMSTool.PSW);
      int msgId = 1000;
      try {
        content = java.net.URLEncoder.encode(content, "GBK");
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
      String strSendURL =
          SMSTool.URL + "cmd=send&uid=" + SMSTool.UID + "&psw=" + pswMd5 + "&mobiles=" + mobile
              + "&msgid=" + msgId + "&msg=" + content;
      String returnMsg = httpGet(strSendURL);
      return returnMsg;
    } else {
      try {
        content = java.net.URLEncoder.encode(content, "UTF-8");
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
      String[] mobileArrays = mobile.split(",");
      String strSendURL =
          SMSTool.URL_V2 + "userId=" + SMSTool.UID_V2 + "&password=" + SMSTool.PSW_V2
              + "&pszMobis=" + mobile + "&pszMsg=" + content + "&iMobiCount=" + mobileArrays.length
              + "&pszSubPort=*";
      String returnMsg = httpGet(strSendURL);
      if (StringUtils.isEmpty(returnMsg)) {
        return "-1000";
      }
      returnMsg = domxml(returnMsg);
      if (returnMsg == null) {
        return "-1000";
      }

      long code = Long.parseLong(returnMsg);
      if (code < 0) {
        return "" + code;
      }
      return "100";
    }
  }

  public static String domxml(String xmlStr) {
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setValidating(false);
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(new InputSource(new ByteArrayInputStream(xmlStr.getBytes("utf-8"))));
      // 获得根元素结点
      Element root = doc.getDocumentElement();
      return root.getTextContent();
    } catch (Exception e) {
      log.error("xml={},exception={}", xmlStr, e);
      return null;
    }
  }

  /**
   * 发 送 短 信 （Post方式）
   * 
   * @param mobile 电话号码，多个电话号码可以用逗号","分隔
   * @param content 短信类容
   * @return 状态码 （100 成功 101失败 102验证失败(密码不对) 103号码有错(接收号码格式错误) 104内容有错(敏感内容) 105操作频率过快(每秒十次)
   *         106限制发送(无条数) 107参数不全）
   */
  public static String sendMsgByPost(String mobile, String content) {
    String pswMd5 = MD5Encode(SMSTool.PSW);
    int msgId = 1000;
    try {
      content = java.net.URLEncoder.encode(content, "GBK");//
      String strSendURL =
          "cmd=send&uid=" + SMSTool.UID + "&psw=" + pswMd5 + "&mobiles=" + mobile + "&msgid="
              + msgId + "&msg=" + content + "";
      String returnMsg = httpPost(SMSTool.URL, strSendURL);
      return returnMsg;
    } catch (Exception ex) {
      System.out.println("Exception:" + ex.getMessage());
      return "101";
    }

  }

  public static void main(String args[]) throws UnsupportedEncodingException {
    String phones = null;
    String msg = "测试信息【微派送】";
    if (args.length > 1) {
      phones = args[0];
      msg = args[1];
      String re = sendMsgByGet(phones, msg);
      System.out.println(re);
    }
    
    String s = "ddd,gg";
    System.out.println(s.split(",").length);
  }

}
